package com.myblog.controller;

import com.myblog.pojo.Diary;
import com.myblog.pojo.Wechat;
import com.myblog.service.Diaryservice;
import com.myblog.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
public class Diarycontroller {

    @Autowired
    private Diaryservice diaryservice;

    @RequestMapping("/diary")
    public Object diary(HttpServletRequest request, Model model){
        HttpSession session=request.getSession();
        Wechat wechat=(Wechat)session.getAttribute("wechat");
        if(wechat!=null){
            System.out.println(wechat);
//            model.addAttribute("wxname",wechat.getWxname().toString());
            model.addAttribute("wximage", URLDecoder.decode(wechat.getImageurl().toString()));
            model.addAttribute("wxname",wechat.getWxname());
        }
        return "diary";
    }

    @RequestMapping("finddiary")
    @ResponseBody
    public Object finddiary(){
        List<Diary> diaryList=diaryservice.finddiary();
        for(Diary diary:diaryList){
            Date date=new Date(diary.getDatatime().getTime());
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(date);
            diary.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
            diary.setMonth(String.valueOf(calendar.get(Calendar.MONTH)+1));
            diary.setDay(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
        }
//        System.out.println(diaryList);
        return JsonData.buildSuccess(diaryList);
    }
}
